package com.example.demo.controller;

import com.example.demo.common.AjaxResult;
import com.example.demo.common.PasswordUtils;
import com.example.demo.entity.UserQue;
import com.example.demo.entity.Userinfo;
import com.example.demo.service.UserQueService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/usqu")
public class UserQueController {

    @Autowired
    private UserQueService userQueService;
    @Autowired
    private UserService userService;

    /**
     *  获取密保问题
     */
    @RequestMapping("/initques")
    public AjaxResult getQuestion(Integer uid) {
        if (uid <= 0) {
            return AjaxResult.fail(-1, "非法参数!");
        }
        UserQue userQue = userQueService.getQuestion(uid);
        if (userQue == null) {
            return AjaxResult.fail(-1, "非法用户!");
        }
        return AjaxResult.success(userQue.getQuestion());
    }

    /**
     *  验证密保的答案正确性
     */
    @RequestMapping("/check")
    public AjaxResult checkQuestion(UserQue userQue, String password) {
        // System.out.println(userQue);
        if (userQue == null || !StringUtils.hasLength(userQue.getAnswer())
                            || userQue.getUid() <= 0) {
            return AjaxResult.fail(-1, "非法参数!");
        }
        // 验证密保
        if (PasswordUtils.check(userQue.getAnswer(), userQueService.checkQuestion(userQue.getUid()))) {
            // 密保无误后, 设置密码
            Userinfo userinfo = userService.getUserById(userQue.getUid());
            if (userinfo == null) {
                return AjaxResult.fail(-1, "非法请求!");
            }
            // 判断设置的密码和数据库中的密码是否相同
            if (PasswordUtils.check(password, userinfo.getPassword())) {
                // 修旧密码相同
                return AjaxResult.fail(-4, "参数错误!");
            }
            // 设置新的密码
            userinfo.setPassword(PasswordUtils.encrypt(password));
            // 解冻账号
            userinfo.setState(1);
            userService.setUserState(userinfo.getState(), userinfo.getId());
            return AjaxResult.success(userService.updPassword(userinfo));
        }
        return null;
    }
}
